<template>
  <div id="addSilverBank">
    <c-title :hide="false" :text="step == 1 ? '添加银行卡' : '验证手机号'"> </c-title>
    <div class="formList" v-if="step == 1">
      <div class="formUser">
        <lineInp :val="form.name" :place="'请输入持卡人姓名'" :title="'姓名'" :Td="'name'" @valInp="valInp"></lineInp>
        <lineInp :val="form.card" istype='number' :place="'请输入卡号'" :title="'卡号'" :Td="'card'" @valInp="valInp"></lineInp>
      </div>
      <div class="tips">注：后续只能绑带该持卡人的银行卡</div>
      <div class="formUser">
        <lineInp :val="form.bank" :place="'请选择所属银行'" :title="'选择银行'" :link="true" :Td="'bank'" @childParams="childParams" @valInp="valInp"></lineInp>
        <lineInp :val="radioCard" :place="'请选择银行卡类型'" :title="'卡类型'" :link="true" :Td="'card_type'" @valInp="valInp" @childParams="childParams"></lineInp>

        <template v-if="form.card_type && form.card_type == 2">
          <lineInp :val="form.cvv2" istype='number' :place="'卡背面末三位'" :title="'安全码'" :Td="'cvv2'" @valInp="valInp"></lineInp>
          <lineInp :val="form.valid_day" :place="'请选择月份/年份'" :title="'有效期'" :link="true" :Td="'valid_day'" @valInp="valInp" @childParams="childParams"></lineInp>
        </template>

        <lineInp :val="form.identity" :place="'请输入证件号'" :title="'身份证'" :Td="'identity'" @valInp="valInp"></lineInp>
        <lineInp :val="form.mobile" istype='tel' :place="'请输入银行卡预留手机号'" :title="'手机号'" :Td="'mobile'" @valInp="valInp"></lineInp>
      </div>
    </div>

    <div class="posbtn set-pc-style">
      <div class="btn" @click="next" v-if="step == 1">下一步</div>
      <div class="btn" @click="confirmBtn" v-if="step == 2">确认</div>
    </div>
    <div class="verifyMobile" v-if="step == 2">
      <div class="verfyBox">
        <div class="top">接受验证码：{{ form.mobile }}</div>
        <div class="verfyTips">绑带银行卡需要短信确认</div>
      </div>
      <van-field v-model="sms" v-if="imgcodeShow" center clearable label="图形验证码" placeholder="请输入右侧图形验证码">
        <template #button>
          <img :src="imgcode" style="width: 3.594rem; height: 1.5rem;" @click="getimgdata()" />
        </template>
      </van-field>
      <van-field v-model="smsMobile" center clearable label="短信验证码" placeholder="请输入短信验证码">
        <template #button>
          <van-button size="small" type="primary" @click="checkCodeMethod" v-if="!btnTag">发送验证码</van-button>
          <div v-else class="countTxt">
            <span style="font-size: 0.6875rem; color: #666;">(已发送)</span>
            {{btnText}}</div>
        </template>
      </van-field>
    </div>
    <!-- 银行卡弹窗 -->
    <van-popup v-model="bankShow" position="bottom" :style="{ height: '50%' }" round>
      <van-nav-bar title="所属银行" left-text="取消" right-text="确认" @click-left="bankShow = false" @click-right="onClickRight">
        <template #left> 取消 </template>
        <template #right> 确认 </template>
      </van-nav-bar>
      <div class="coverBox">
        <van-radio-group v-model="radio">
          <div class="banklis" v-for="(item, index) in bankArr" :key="index">
            <div class="name">{{ item }}</div>
            <van-radio :name="item"></van-radio>
          </div>
        </van-radio-group>
      </div>
    </van-popup>
    <!-- 银行卡类型 -->
    <van-popup v-model="cardShow" position="bottom" :style="{ height: '25%' }" round>
      <van-nav-bar title="银行卡类型" left-text="取消" right-text="确认" @click-left="cardShow = false" @click-right="onClickRight_cardShow">
        <template #left> 取消 </template>
        <template #right> 确认 </template>
      </van-nav-bar>
      <van-radio-group v-model="radioCard">
        <div class="banklis" v-for="(item, index) in bankCard" :key="index">
          <div class="name">{{ item.name }}</div>
          <van-radio :name="item.name"></van-radio>
        </div>
      </van-radio-group>
    </van-popup>
    <!-- 有效期至 -->
    <van-popup v-model="timeShow" position="bottom" round>
      <van-datetime-picker @confirm="onClickRight_timeShow" @cancel="timeShow = false" v-model="currentDate" type="year-month" title="选择年月" :max-date="maxDate" :formatter="formatter" />
    </van-popup>
  </div>
</template>
<script>
import lineInp from "./components/lineInp";
import { Toast } from "vant";
export default {
  data() {
    return {
      form: {
        name: "",
        card: "",
        bank: "",
        card_type: "",
        identity: "",
        mobile: "",
        cvv2: "",
        valid_day: ""
      },
      step: 1,
      // 所属银行弹窗
      bankShow: false,
      // 信用卡类型弹窗
      cardShow: false,
      radio: "",
      radioCard: "",
      bankArr: ["中信银行", "上海银行", "光大银行", "民生银行", "北京银行", "平安银行", "交通银行", "招行银行", "招行银行", "广发银行", "华夏银行", "建设银行", "农业银行", "浦发银行", "邮储银行"],
      bankCard: [
        { name: "储蓄卡", id: 1 },
        { name: "信用卡", id: 2 }
      ],
      // 有效期选择
      timeShow: false,
      maxDate: new Date(),
      currentDate: new Date(),

      // 第二步，验证码
      // 图形验证码
      imgcode: "",
      // 是否开启图形验证码
      imgcodeShow: false,
      sms: "",
      smsMobile: "",
      btnText: "获取验证码",
      timer: null,
      btnTag: false,
      order_pay_id:''
    };
  },
  activated() {
    if (this.$route.params.order_pay_id) {
      this.order_pay_id = this.$route.params.order_pay_id;
    }
  },
  methods: {
    //获取图片验证码
    getimgStatus() {
      $http
        .get("plugin.silver-point-pay.frontend.union-card.captcha-status",{},' ')
        .then(res => {
          if (res.data.status == 1) {
            this.imgcodeShow = true;
            this.getimgdata();
          } else {
            this.imgcodeShow = false;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 验证发送短信验证码
    checkCodeMethod() {
      if (this.imgcodeShow) {
        // 如果开启了图形验证码
        this.checkCaptcha();
      } else {
        this.firstNext();
      }
    },
    checkCaptcha() {
      $http
        .get("plugin.silver-point-pay.frontend.union-card.captcha", { code: this.sms },' ')
        .then(res => {
          console.log(res);
          if (res.result == 1) {
            this.firstNext();
          } else {
            this.getimgdata();
            this.$dialog.alert({ message: res.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    confirmBtn() {
      if (this.fun.isTextEmpty(this.smsMobile)) {
        this.$dialog.alert({ message: "请输入短信验证码" });
        return;
      }
      this.checkPhoneCode();
    },
    //获取图片验证码
    getimgdata() {
      $http
        .get("home-page.getCaptcha",{},' ')
        .then(res => {
          if (res.data.captcha) {
            this.imgcode = res.data.captcha.img;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 时间戳转日期
    timestampToTime: function (timestamp) {
      if (!Number(timestamp) || timestamp == "") {
        return "";
      }
      let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear();
      let M = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;

      return `${M}${Y}`;
    },
    // 有效期方法
    onClickRight_timeShow(e) {
      this.form.valid_day = this.timestampToTime(e);
      this.timeShow = false;
    },
    onClickRight() {
      // 所属银行确认方法
      this.form.bank = this.radio;
      this.bankShow = false;
    },
    onClickRight_cardShow() {
      //银行卡类型
      this.form.card_type = this.radioCard == "储蓄卡" ? 1 : 2;
      this.cardShow = false;
    },
    valInp(e) {
      this.form[e.type] = e.value;
    },
    next() {
      console.log(this.form, "ddddd11111111");
      if (this.step == 1) {
        if (this.verify()) {
          // 第二部 验证图形码,手机验证码
          this.step = 2;
          this.getimgStatus();
        }
      }
    },
    firstNext() {
      let json = {
        card: this.form.card,
        bank: this.form.bank,
        name: this.form.name,
        identity: this.form.identity,
        mobile: this.form.mobile,
        card_type: this.form.card_type
      };
      if (this.form.card_type == 2) {
        json.valid_day = this.form.valid_day;
        json.cvv2 = this.form.cvv2;
      }
      $http
        .post("plugin.silver-point-pay.frontend.union-card.bind-card", json, " ")
        .then(res => {
          console.log(res);
          let resdata = res.data;
          if (res.result == 1) {
            this.token = resdata.token;
            this.pay_union_card_id = resdata.pay_union_card_id;
            this.sendCodeAnimation();
          } else {
            this.$dialog.alert({ message: res.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 倒计时
    sendCodeAnimation() {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        Toast.success("验证码已发送");
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
            this.btnText = this.count + "s";
            this.btnTag = true;
          } else {
            this.btnTag = false;
            this.btnText = "获取验证码";
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    // 短信验证绑定
    checkPhoneCode() {
      let json = { code: this.smsMobile, token: this.token, pay_union_card_id: this.pay_union_card_id };
      $http
        .post("plugin.silver-point-pay.frontend.union-card.sms", json, " ")
        .then(res => {
          if (res.result == 1) {
            if(this.order_pay_id){
              this.$dialog.alert({ message: res.msg }).then(()=>{
                this.$router.push(this.fun.getUrl("SilverPay",{order_pay_id:this.order_pay_id},{money:this.$route.query.money,sn:this.$route.query.sn}));
              });
            }else{
              this.$dialog.alert({ message: res.msg }).then(()=>{
                this.$router.push(this.fun.getUrl("SilverBankList"));
              });
            }
          } else {
            this.$dialog.alert({ message: res.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    verify() {
      if (this.fun.isTextEmpty(this.form.name)) {
        this.$dialog.alert({ message: "请输入持卡人姓名" });
        return false;
      }
      if (this.fun.isTextEmpty(this.form.card)) {
        this.$dialog.alert({ message: "请输入卡号" });
        return false;
      }
      if (this.fun.isTextEmpty(this.form.bank)) {
        this.$dialog.alert({ message: "请选择所属银行" });
        return false;
      }
      if (this.fun.isTextEmpty(this.form.card_type)) {
        this.$dialog.alert({ message: "请选择银行卡类型" });
        return false;
      }
      if (this.fun.isTextEmpty(this.form.identity)) {
        this.$dialog.alert({ message: "请输入证件号" });
        return false;
      }
      if (this.fun.isTextEmpty(this.form.mobile)) {
        this.$dialog.alert({ message: "请输入银行卡预留手机号" });
        return false;
      }
      if (this.form.card_type == 2) {
        // 信用卡多验证两个 cvv2 valid_day
        if (this.fun.isTextEmpty(this.form.cvv2)) {
          this.$dialog.alert({ message: "请输入卡背面末三位" });
          return false;
        }
        if (this.fun.isTextEmpty(this.form.valid_day)) {
          this.$dialog.alert({ message: "请选择月份/年份" });
          return false;
        }
      }
      return true;
    },
    childParams(type) {
      if (type == "valid_day") {
        // 有效期
        this.timeShow = true;
      } else if (type == "card_type") {
        // 卡类型
        this.cardShow = true;
      } else if (type == "bank") {
        // 所属银行
        this.bankShow = true;
      }
    }
  },
  components: { lineInp }
};
</script>
<style lang="scss" scoped>
.coverBox {
  height: 85%;
  overflow-y: scroll;
}

.banklis {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.7813rem 0.9375rem;
}
// 验证手机号
.verifyMobile {
  padding: 0.625rem;

  .verfyBox {
    background: #fff;
    border-radius: 0.3125rem;
    padding: 1.0938rem 0.875rem;
    display: flex;
    flex-direction: column;

    .top {
      font-size: 0.9375rem;
      font-weight: 400;
      color: #333;
    }

    .verfyTips {
      font-size: 0.75rem;
      font-weight: 400;
      color: #666;
      margin-top: 0.3125rem;
    }
  }
}

.formList {
  padding: 0 0.625rem;

  input {
    border: none;
  }

  .formUser {
    background: #fff;
    border-radius: 0.3125rem;
    margin-top: 0.625rem;
  }

  .tips {
    font-size: 0.6875rem;
    font-weight: 400;
    color: #868686;
    text-align: left;
    margin: 0.5938rem 0;
  }
}

.posbtn {
  position: fixed;
  width: 100%;
  height: 3.125rem;
  bottom: 0;
  left: 0;
  padding: 0.3125rem 1.7188rem;
  background: #fff;

  .btn {
    height: 2.5rem;
    font-size: 1rem;
    font-weight: 400;
    color: #fff;
    background: #f51d1d;
    border-radius: 0.3125rem;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.countTxt {
  color: #f14e4e;
  font-size: 0.6875rem;
}
</style>
